package com.fengwk.user.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fengwk.support.code.Sequence;
import com.fengwk.support.util.CodeUtils;
import com.fengwk.support.util.WebUtils;
import com.fengwk.user.dao.UsTokenDao;
import com.fengwk.user.face.entity.UsToken;
import com.fengwk.user.face.model.Token;
import com.fengwk.user.service.TokenService;

@Service
public class TokenServiceImpl implements TokenService {

	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private UsTokenDao usTokenDao;
	
	@Override
	public Token createToken(String channel, Long userId, int timeout) {
		UsToken usToken = new UsToken();
		usToken.setRecordId(Sequence.next());
		usToken.setChannel(channel);
		usToken.setToken(CodeUtils.uuid());
		usToken.setUserId(userId);
		usToken.setLoginIp(WebUtils.getRemoteIp(request));
		usToken.setLoginTime(System.currentTimeMillis());
		usToken.setTimeout(timeout);
		usTokenDao.insert(usToken);
		return usTokenToToken(usToken);
	}
	
	@Override
	public Token reLoginToken(String channel, String token) {
		UsToken usToken = usTokenDao.findByChannelAndToken(channel, token);
		usToken.setLoginIp(WebUtils.getRemoteIp(request));
		usToken.setLoginTime(System.currentTimeMillis());
		usTokenDao.updateByRecordId(usToken);
		return usTokenToToken(usToken);
	}

	@Override
	public Token getToken(String channel, String token) {
		UsToken usToken = usTokenDao.findByChannelAndToken(channel, token);
		return usTokenToToken(usToken);
	}

	private Token usTokenToToken(UsToken usToken) {
		Token token = null;
		long loginTime = usToken.getLoginTime();
		long timeout = usToken.getTimeout();
		if (timeout == UsToken.TIMEOUT_INVALID 
				|| System.currentTimeMillis() - loginTime <= timeout * 1000) {
			token = new Token();
			token.setChannel(usToken.getChannel());
			token.setToken(usToken.getToken());
			token.setUserId(usToken.getUserId());
			token.setLoginIp(usToken.getLoginIp());
			token.setLoginTime(usToken.getLoginTime());
			token.setTimeout(usToken.getTimeout());
		}
		return token;
	}

}
